<?php
class ModelGenAction extends Action
{
	function _initialize()
    {
        if(Session::get("prj_path") == "")
        {
            $this->assign("jumpUrl",url("listPrj","Project"));
            $this->error("请先选择项目");
        }
    }

    function index()
    {
		$config = include Session::get('prj_path').'/Conf/config.php';
		$config['DB_PORT'] = empty($config['DB_PORT'])?3306:$config['DB_PORT'];
		$db = mysql_connect($config['DB_HOST'].":".$config['DB_PORT'],$config['DB_USER'],$config['DB_PWD']);
		mysql_select_db($config['DB_NAME'],$db);
		$rs = mysql_query('SHOW TABLES',$db) or $this->error("无法获取数据表列表！");
		$ModelList = array();
		while($table = mysql_fetch_array($rs))
		{
			$model = str_replace($config['DB_PREFIX'],'',$table[0]);
			//按新版TP要求,把下划线连接的变成驼峰命名
			$model = $this->parseName($model,1);

			$ModelList[$model] = $model;
		}
		
		$FieldList = array();
		if(!empty($_GET["Model"]))
		{
			$tableName = $config['DB_PREFIX'].$this->parseName($_GET["Model"]);
			$rs = mysql_query('SHOW COLUMNS FROM '.$tableName,$db) or $this->error("无法获取字段列表！");
			while($field = mysql_fetch_array($rs))
			{
				$FieldList[$field['Field']] = $field['Field'];
			}
		}

		mysql_close($db);		

		$this->assign("ModelList",$ModelList);
		$this->assign("FieldList",$FieldList);
		$this->assign("pageFile","ModelGen:index");
		$this->layout();
	}

	function save()
	{
		if(empty($_POST["modelname"]))
			$this->error("你没有选择要生成的Model!");

		$modelfile = Session::get("prj_path")."/Lib/Model/".$_POST["modelname"]."Model.class.php";
		if(is_file($modelfile) && $_POST["overwrite"]!="on")
				$this->error("存在同名的Model文件: ".$modelfile);

		$content = '<?php
class '.$_POST["modelname"].'Model extends Model
{
';
		if($_POST["linktype"]!="") //关联选项
			$content .= $this->plink();
		
		if($_POST["viewmodel"]=="on")
			$content .= $this->viewmodel();

		if($_POST["autoFields"][0]!="")	//存在自动填充的规则	
			$content .= $this->auto();

		if($_POST["validateFields"][0]!="")	//存在自动校验的规则	
			$content .= $this->validate();

		$content .= '}
?>';
		file_put_contents($modelfile,$content);

		$this->success("Model文件已生成: ".$modelfile);
	}

	private function viewmodel()
	{
		$content = '	protected $viewModel = true;
	 
	// 视图模型中的字段定义 
	protected $viewFields = array( 
		"Model1"=>array("field1","field2","field3"), 
		"Model2"=>array("field1","field2") 
	); 

	// 视图关联的where条件 
	protected $viewCondition = array("Model1.field1" => array("eqf","Model2.field1")); 
	 
	// 视图模型的主键
	Public function getPk() { 
		return "Model1.field1"; 
	}

';
		return $content;			
	}

	private function auto()
	{
		$content = '	// 自动填充规则
	var $_auto = array(
';
		for($i=0;$i<count($_POST["autoFields"]);$i++)
		{
			if(empty($_POST["autoFields"][$i]))
				continue;
			else
			{
				$content .= '		array("'.$_POST["autoFields"][$i].'","'.$_POST["content"][$i].'","'.$_POST["when"][$i].'","'.$_POST["autotype"][$i].'"),
';
			}
		}
		$content .= '	); 

';
		return $content;
	}

	private function validate()
	{
		$content = '	// 自动校验规则
	var $_validate = array(
';
		for($i=0;$i<count($_POST["validateFields"]);$i++)
		{
			if(empty($_POST["validateFields"][$i]))
				continue;
			else
			{
				$content .= '		array("'.$_POST["validateFields"][$i].'","'.$_POST["rule"][$i].'","'.$_POST["message"][$i].'",'.$_POST["condition"][$i].',"'.$_POST["append"][$i].'"),
';
			}
		}
		$content .= '	); 

';
		return $content;
	}

	private function plink()
	{
		$linkvar = empty($_POST["linkvar"])?"linkvar":$_POST["linkvar"];
		$linkvar = str_replace('$','',$linkvar);

		$content = '	var $'.$linkvar.';

	// 关联模型定义
	var $_link = array( 
		array(
			"mapping_type"=>'.$_POST["linktype"].', 
			"class_name"=>"Foreign_Model", 
			"foreign_key"=>"", 
			"mapping_name"=>"'.$linkvar.'", 
		 ) 
	);

';
		return $content;
	}
}
?>